var page_content = {};

$(function()
{
	$( "#pagelist-0" ).nestedSortable({
		listType: "ul",
		handle: 'div',
        items: 'li',
        toleranceElement: '> div',
        placeholder: 'placeholder',
        forcePlaceholderSize: true,
		helper:	'clone',
		revert: 250,
		isTree: true,
		expandOnHover: 700,
		startCollapsed: true,
		stop: function(event, ui)
		{
			$parent = $(ui.item).parent().parent();
			if($parent.size() == 0)
			{
				$parent = $(ui.item).parent();
				$parent.data("pageid","0");

				$children = $parent.find("> li").map(function(i, el)
				{
					return parseInt($(el).data("pageid"));

				}).get();
			}
			else
			{
				$children = $parent.find("> ul > li").map(function(i, el)
				{
					return parseInt($(el).data("pageid"));

				}).get();	
			}

			var parentid = parseInt($parent.data("pageid"));
			parentid = (isNaN(parentid)?0:parentid);

			$.post("/manager/pages/move",
			{
				"parentid" : parentid,
				"children" : $children
			}, function(data)
			{
				
			}, "json");
		}
	});

	$(".delete-page").submit(function(e){
		return confirm("WARNING: This action will DELETE this page and any CHILD PAGES as well!\n\nAre you sure you want to proceed?");
	})

	$(".quick-edit").click(function(e)
	{
		e.preventDefault();
		var $this = $(this);

		if($this.data("showing") == false)
		{
			$(".quick-edit").removeClass("btn-info");
			$(".quick-edit").find("i");
			$(".quick-edit").data("showing", false);
			$("#pagelist-container").removeClass('col-lg-12').addClass('col-lg-8');
		}
		else
		{
			$("#quick-edit").hide();
			$("#pagelist-container").addClass('col-lg-12').removeClass('col-lg-8');
		}
		
		$this.toggleClass("btn-info");
		$this.find("i");
		$("#quick-edit").toggle(($this.data("showing") == false));
		$this.data("showing", !$this.data("showing"));

		if($this.data("showing") == true)
		{
			$("#quick-edit-content")
				.html("<p class='lead' style='text-align:center'><i class='fa fa-spinner fa-spin'></i> Loading&hellip;")
				.load('/manager/pages/quickedit/'+$this.data('pageid'));
			
		}
	});

	$("#quickedit-form").livequery(function()
	{
		$(this).ajaxForm({
			beforeSubmit: function()
			{
				$("#quickedit-save").button("loading");
			},
			success: function(data, statusText, xhr, $form)
			{
				// TODO: insert Growl notification
				alert(data.message + "!");
				$("#quickedit-save").button("reset");
			},
			"dataType":"json"
		});
	});

	$("#name.newpage").blur(function(event) {
		$.post("/manager/pages/getslug", {
			"str":$(this).val()
		}, function(data)
		{
			$("#slug").val(data.val);
		})
	});

	$('[data-toggle="tooltip"]').livequery(function()
	{
		$(this).tooltip({
			container:"body",
			animation:false
		});
	});

	$("#addrowbutton").click(function(e)
	{
		e.preventDefault();
		$.observable(page_content.rows).insert({"blocks":[]});
	});

	$(document).on("click", ".deleterowbutton", function(e)
	{
		e.preventDefault();
		if(confirm("Are you sure you want to delete this entire row?"))
		{
			var dataItem = $.view(this).parent.parent.data;
			$.observable(dataItem.rows).remove($.view(this).index);
		}
	});

	$(document).on("click", ".addblockbutton", function(e)
	{
		e.preventDefault();

		var dataItem = $.view(this).data;
		//var current_span = dataItem.span;

		$.observable(dataItem.blocks).insert({"span":3, "offset":0, "content":""});
	});

	//$("#content-editor").ckeditor();
	$(".editor").livequery(function()
	{
		$(".editor").each(function()
		{
			var $editor = $(this);

			if(!$editor.data("ckeditorInstance"))
			{
				$editor.ckeditor({toolbar:"Standard"});
			}

			if($editor.data("processed") == null)
			{
				$editor.data("processed", "true");
				$editor.data("ckeditorInstance").on('change', function(e)
				{
					var dataItem = $.view($editor).data;
					$.observable(dataItem).setProperty("content", e.editor.getData());
				});
			}

		});
	});

	$(document).on("click", ".increase-span, .decrease-span", function(e)
	{
		e.preventDefault();

		var dataItem = $.view(this).data;
		var current_span = dataItem.span;

		if($(this).is(".increase-span"))
		{
			current_span++;
			if(current_span >= 12)
			{
				current_span = 12;
			}
		}
		else if($(this).is(".decrease-span"))
		{
			current_span--;
			if(current_span < 3)
			{
				current_span = 3;
			}
		}

		$.observable(dataItem).setProperty("span", current_span);
	});

	$(document).on("click", ".increase-left-margin, .decrease-left-margin", function(e)
	{
		e.preventDefault();

		var dataItem = $.view(this).data;
		var current_offset = dataItem.offset;

		if($(this).is(".increase-left-margin"))
		{
			current_offset++;
			if(current_offset >= 9)
			{
				current_offset = 9;
			}
		}
		else if($(this).is(".decrease-left-margin"))
		{
			current_offset--;
			if(current_offset < 0)
			{
				current_offset = 0;
			}
		}

		$.observable(dataItem).setProperty("offset", current_offset);
	});

	$(document).on("click", ".delete-block", function(e)
	{
		e.preventDefault();
		if(confirm("Are you sure you want to delete this block?"))
		{
			var dataItem = $.view(this).parent.data;
			$.observable(dataItem).remove($.view(this).index);
		}
	});

	if(typeof(page_content) != "undefined")
	{
		$.observable(page_content).observeAll(function()
		{
			$('.tooltip').hide();
			$("#page_content").val(JSON.stringify(page_content));
			//$.templates("#tmpl_page_row").link("#pagecontent", page_content);
		});
		$("#page_content").val(JSON.stringify(page_content));

		$.templates({
			tmpl_page_row: "#tmpl_page_row"
		});
		$.templates("#tmpl_page_row").link("#pagecontent", page_content);
	}

});